package com.tsh.chat.controller;

import com.fasterxml.jackson.core.JacksonException;
import com.tsh.chat.domain.ChatHistory;
import com.tsh.chat.domain.MessageBody;
import com.tsh.chat.domain.Personality;
import com.tsh.chat.service.PersonalitySimulatorService;
import com.tsh.chat.service.PromptService;
import com.tsh.chat.util.ChatUtil;
import com.tsh.common.core.web.controller.BaseController;
import com.tsh.common.core.web.domain.AjaxResult;
import com.tsh.common.security.utils.SecurityUtils;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/simulator")
public class PersonalSimulatorController extends BaseController {

    @Autowired
    private PersonalitySimulatorService personalitySimulatorService;

    @Autowired
    private PromptService promptService;

    /**
     * 添加更新人设描述信息
     */
    @PostMapping("/characterDesc")
    public AjaxResult setCharacterDesc(@RequestBody MessageBody messageBody) {
        if(messageBody.getUuid() != SecurityUtils.getUserId()) return error("用户名ID不合法");
        String message = messageBody.getMessage();
        List<Personality> list = personalitySimulatorService.getPersonality(messageBody.getUuid());
        if(list.isEmpty()){
            Date nowadays = new Date();
            try{
                String characterDesc = ChatUtil.updateCharacterDescSSE("", message, nowadays, nowadays);
                String characterAchieve = ChatUtil.updateCharacterAchievementSSE("", message, nowadays, nowadays);
                String characterRelation = ChatUtil.updateCharacterRelationSSE("", message, nowadays, nowadays);
                Personality personality = new Personality();
                personality.setUserId(messageBody.getUuid());
                personality.setDescription(characterDesc);
                personality.setAchievement(characterAchieve);
                personality.setRelationship(characterRelation);
                personalitySimulatorService.insertPersonality(personality);
                int personalityId = personalitySimulatorService.getLastInsertId();
                HashMap<String, Integer> uniqueId = new HashMap<>();
                uniqueId.put("personalityId", personalityId);
                personalitySimulatorService.insertPromptHistory(messageBody.getUuid(), message);
                int promptId = personalitySimulatorService.getLastInsertId();
                uniqueId.put("promptId", promptId);
                return AjaxResult.success("添加人设成功", uniqueId);
            }catch (JacksonException e){
                System.err.println("更新人设信息异常!");
                return error(e.getMessage());
            }
        }else{
            Date nowadays = new Date();
            String oldDesc = list.get(0).getDescription();
            String oldAchieve = list.get(0).getAchievement();
            String oldRelation = list.get(0).getRelationship();
            Date oldTime = list.get(0).getDate();
            try{
                String characterDesc = ChatUtil.updateCharacterDescSSE(oldDesc, message, oldTime, nowadays);
                String characterAchieve = ChatUtil.updateCharacterAchievementSSE(oldAchieve, message, oldTime, nowadays);
                String characterRelation = ChatUtil.updateCharacterRelationSSE(oldRelation, message, oldTime, nowadays);
                Personality personality = new Personality();
                personality.setUserId(messageBody.getUuid());
                personality.setDescription(characterDesc);
                personality.setAchievement(characterAchieve);
                personality.setRelationship(characterRelation);
                personality.setId(list.get(0).getId());
                personalitySimulatorService.updatePersonality(personality);
                personalitySimulatorService.insertPromptHistory(messageBody.getUuid(), message);
                HashMap<String, Integer> uniqueId = new HashMap<>();
                int promptId = personalitySimulatorService.getLastInsertId();
                uniqueId.put("promptId", promptId);
                uniqueId.put("personalityId", -1);
                return AjaxResult.success("添加人设信息成功", uniqueId);
            }catch (JacksonException e){
                System.err.println("更新人设信息异常!");
                return error(e.getMessage());
            }
        }
    }

    /**
     * 获取人设描述记录历史
     */
    @GetMapping("/promptHistory")
    public AjaxResult getPromptHistory(@RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()) return error();
        return AjaxResult.success("获取记录成功", personalitySimulatorService.getPromptHistoryByUserId(userId));
    }

    /**
     * 根据id删除人设描述信息
     */
    @DeleteMapping("/delPrompt")
    public AjaxResult delPersonalityPrompt(@RequestParam int id, @RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()){
            return error("无权删除!");
        }
        return toAjax(personalitySimulatorService.deletePromptHistoryById(id));
    }

    /**
     * 根据id删除人设
     */
    @DeleteMapping("/delPersonality")
    public AjaxResult delPersonality(@RequestParam int id, @RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()){
            return error("无权删除!");
        }
        if(personalitySimulatorService.deletePersonality(id) > 0){
            personalitySimulatorService.deletePromptHistoryByUserId(userId);
            return success();
        }
        return error("没有可以删除的人设");
    }

    /**
     * 查询人设id
     */
    @GetMapping("/personalityId")
    public AjaxResult getPersonalityId(@RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()) return error();
        List<Personality> personalityList = personalitySimulatorService.getPersonality(userId);
        if(personalityList.isEmpty()){
            final int NOT_FOUND_ID = -1;
            return AjaxResult.success(NOT_FOUND_ID);
        }
        return success(personalityList.get(0).getId());
    }

    /**
     * 查询人设信息
     */
    @GetMapping("/personality")
    public AjaxResult getPersonality(@RequestParam int id, @RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()){
            return error("无权获取!");
        }
        List<Personality> personalityList = personalitySimulatorService.getPersonality(userId);
        if(personalityList.isEmpty()){
            return success("当前无人设");
        }
        return AjaxResult.success("获取成功!", personalityList.get(0));
    }


    /**
     * 获取对话记录
     */
    @GetMapping("/chatHistory")
    public AjaxResult chatHistory(@RequestParam int userId) {
        List<ChatHistory> chatHistoryList = personalitySimulatorService.getChatHistoryByUserId(userId);
        if (chatHistoryList != null && !chatHistoryList.isEmpty()) {
            return AjaxResult.success("查询成功", chatHistoryList);
        } else {
            return AjaxResult.success("当前聊天记录为空");
        }
    }

    /**
     * 删除所有对话记录
     */
    @DeleteMapping("/delChatHistory")
    public AjaxResult delChatHistory(@RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()){
            return error("当前用户不能删除");
        }
        return toAjax(personalitySimulatorService.deleteChatHistoryByUserId(userId));
    }

    /**
     * 重构人设
     */
    @PostMapping("/rebuild")
    public AjaxResult rebuildPersonality(@RequestParam int id, @RequestParam int userId) {
        if(userId != SecurityUtils.getUserId()){
            return error("重构失败，用户无权限");
        }
        Personality newPersonality = promptService.rebuildPersonality(userId);
        newPersonality.setId(id);
        return toAjax(personalitySimulatorService.updatePersonality(newPersonality));
    }
}
